package cn.gok.thread;

import java.util.Random;

//消费者线程
public class ConsumeThread extends Thread {
    private WareHouse wareHouse;

    public ConsumeThread(WareHouse wareHouse) {
        this.wareHouse = wareHouse;
    }

    private Random rd = new Random();

    @Override
    public void run() {
        while (true) {
            synchronized (wareHouse) {
                String product = wareHouse.consume();
                if (product != null) {
                    System.out.println("从仓库消费:" + product);
                    continue;
                }
                //当仓库为null的时候，需要线程进入等待的状态
                System.out.println("仓库为空，无法进行消费商品，进入等待状态");
                try {
                    wareHouse.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (String.class) {
                    wareHouse.consume();
                    if (product != null) {
                        System.out.println("结束等待，从仓库消费：" + product);
                    } else {
                        continue;
                    }
                }
            }
            try {
                Thread.sleep(rd.nextInt(1500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
